package com.example.sql.manager.filters;

import com.example.sql.manager.common.ResponseEntity;
import com.example.sql.manager.utils.IDUtils;
import com.example.sql.manager.utils.MDCUtils;

import javax.servlet.*;
import java.io.IOException;

public class RequestIdFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 生成请求 ID，并将其存储在 MDC 中
        String requestId = String.valueOf(IDUtils.genRandomId());
        MDCUtils.put(ResponseEntity.TRACE_ID_KEY, requestId);

        /*
         *日志配置文件里这么取
         *<layout class="ch.qos.logback.classic.PatternLayout">
         *    <springProfile name="dev">
         *        <pattern>%d{yyyy-MM-dd HH:mm:ss}[%X{requestId}][%thread] %-5level %logger{50} - %msg%n</pattern>
         *    </springProfile>
         *    <springProfile name="!dev">
         *        <pattern>%d{yyyy-MM-dd HH:mm:ss}[%X{requestId}][%thread] %-5level %logger{50} - %msg%n</pattern>
         *    </springProfile>
         *</layout>
         */

        // 处理请求
        filterChain.doFilter(servletRequest, servletResponse);

        // 在请求处理完成后，从 MDC 中移除请求 ID
        MDCUtils.remove(ResponseEntity.TRACE_ID_KEY);
    }
}
